//
//  SignalRFile.m
//  O2O
//
//  Created by Jinniu on 2018/8/16.
//  Copyright © 2018年 金牛. All rights reserved.
//

#import "SignalRFile.h"
#import <SignalR_ObjC/SignalR.h>
#import "LocalVoiceFile.h"
#import "OrderO2OListModel.h"
#import "NSObject+ViewController.h"
#import "JWBluetoothManage.h"
#import "BluetoothViewController.h"

@interface SignalRFile()
@property (nonatomic,strong) NSArray *array;
@property (nonatomic,strong) OrderO2OListModel *model;
@property (nonatomic,assign) NSInteger count;
@end

@implementation SignalRFile
+(instancetype)createSignalR{
    static SignalRFile * sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
- (instancetype)init{
    self = [super init];
    if (self) {
        SRHubConnection *hubConnection = [SRHubConnection connectionWithURLString:O2ODomain];
        SRHubProxy *chat = (SRHubProxy*)[hubConnection createHubProxy:@"shophub"];
        [chat on:@"NewOrder" perform:self selector:@selector(addMessage:)];
        
        [hubConnection setStarted:^{
            VLog(@"*+*+*+*+**+*+*+*+*+*>>>:Connection Started");
        }];
        __weak typeof(self)weakSelf = self;
        [hubConnection setReceived:^(NSString *message) {
            NSUserDefaults *userfaults = [NSUserDefaults standardUserDefaults];
            VicSingleObject *single=[VicSingleObject getInstance];
            NSDictionary *dic = [message mj_JSONObject];
            weakSelf.array = dic[@"A"];
            if ([single.shopInfoModel.ShopId isEqualToString:[NSString stringWithFormat:@"%@",[weakSelf.array firstObject]]]) {
                if ([dic[@"M"] isEqualToString:@"NewOrder"]) {
                    if ([[userfaults objectForKey:[NSString stringWithFormat:@"%@onString",single.shopInfoModel.ShopId]] isEqualToString:@"开"]) {
                        JWBluetoothManage * manage = [JWBluetoothManage sharedInstance];
                        if (manage.connectedPerpheral!=nil) {
                            [LocalVoiceFile speakVoice:@"您有新的订单,请注意查收"];
                            [ProgressShow alertView1:[weakSelf ViewController].view Message1:@"您有新的订单,请注意查收" cb1:nil];
                            [weakSelf performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:4.0];
                        }else{
                            BluetoothViewController *VC = [BluetoothViewController new];
                            VC.array = weakSelf.array;
                            [[weakSelf ViewController].navigationController pushViewController:VC animated:YES];
                        }
                    }else{
                        [LocalVoiceFile speakVoice:@"您有新的订单,请注意查收,自动接单已关闭，请手动接单或开启自动接单"];
                        [ProgressShow alertView2:[weakSelf ViewController].view Message2:@"您有新的订单,请注意查收" cb2:nil];
                    }
                    [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:@"updateFirstTableViewData"object:nil userInfo:nil]];
                }
            }
            /*
             NSDictionary * dic = (NSDictionary*)message;
             NSArray * Aarr = dic[@"A"];
             if (Aarr.count>1) {
             [self UpdateOrderRequset:Aarr[1]];
             }
             */
        }];
        [hubConnection setConnectionSlow:^{
            VLog(@"*+*+*+*+**+*+*+*+*+*>>>:Connection Slow");
        }];
        
        [hubConnection setReconnecting:^{
            VLog(@"*+*+*+*+**+*+*+*+*+*>>>:Connection Reconnecting");
        }];
        
        //连接成功
        [hubConnection setReconnected:^{
            VLog(@"*+*+*+*+**+*+*+*+*+*>>>:Connection Reconnected");
        }];
        
        //连接关闭
        [hubConnection setClosed:^{
            VLog(@"*+*+*+*+**+*+*+*+*+*>>>:Connection Closed");
        }];
        
        [hubConnection setError:^(NSError *error) {
            VLog(@"*+*+*+*+**+*+*+*+*+*>>>:Connection Error %@",error);
        }];
        // Start the connection
        //开始连接
        [hubConnection start];
    }
    return self;
}

-(void)delayMethod{
    
    NSString *shopId3 = [NSString stringWithFormat:@"%@",[self.array lastObject]];
    [self getOrderInfoDetailsWithOrderId:shopId3];
}
-(void)getOrderInfoDetailsWithOrderId:(NSString*)orderId{
    [ReuserFile getShopOrderInfo:orderId andBackBlock:^(NSDictionary *backDic) {
        if ([backDic[@"status"] isEqualToString:@"1"]) {
            NSArray *array = backDic[@"data"][@"List"];
            self.model = [OrderO2OListModel mj_objectWithKeyValues:[array firstObject]];
            JWBluetoothManage * manage = [JWBluetoothManage sharedInstance];
            if (manage.stage != JWScanStageCharacteristics) {
                [LocalVoiceFile speakVoice:@"请检查打印机的状态"];
                [ProgressShow alertView1:[self ViewController].view Message1:@"请检查打印机的状态" cb1:nil];
                return;
            }
            [LocalVoiceFile speakVoice:@"正在准备打印，请稍后"];
            [ProgressShow alertView1:[self ViewController].view Message1:@"正在准备打印，请稍后" cb1:nil];
            [self performSelector:@selector(delayMethod1) withObject:nil/*可传任意类型参数*/ afterDelay:4.0];
        }else{
            [LocalVoiceFile speakVoice:backDic[@"msg"]];
        }
    }];
}
-(void)delayMethod1{
    JWBluetoothManage * manage = [JWBluetoothManage sharedInstance];
    if (manage.stage != JWScanStageCharacteristics) {
        [LocalVoiceFile speakVoice:@"请检查打印机的状态"];
        [ProgressShow alertView1:[self ViewController].view Message1:@"请检查打印机的状态" cb1:nil];
        return;
    }
    [self printe];
}
- (void)printe{
    JWPrinter *printer = [[JWPrinter alloc] init];
    [printer appendText:[NSString stringWithFormat:@"#%@",_model.OrderSource] alignment:HLTextAlignmentLeft fontSize:HLFontSizeTitleMiddle];
    [printer appendText:_model.ShopName alignment:HLTextAlignmentLeft fontSize:HLFontSizeTitleMiddle];
    [printer appendNewLine];
    [printer appendText:[NSString stringWithFormat:@"订单编号：%@",_model.OId] alignment:HLTextAlignmentCenter fontSize:HLFontSizeTitleSmalle];
    [printer appendText:_model.OrderTime alignment:HLTextAlignmentCenter fontSize:HLFontSizeTitleSmalle];
    [printer appendSeperatorLine];
    [printer appendLeftText:@"商品名称" middleText:@"数量" rightText:@"单价" isTitle:YES];
    for (NSDictionary *dic in _model.Detail) {
        [printer appendLeftText:dic[@"Name"] middleText:[NSString stringWithFormat:@"x%@",dic[@"Count"]] rightText:[NSString stringWithFormat:@"￥%@",dic[@"Price"]] isTitle:NO];
    }
    [printer appendSeperatorLine];
    [printer appendText:[NSString stringWithFormat:@"配送费：￥%@",_model.FreightAmt] alignment:HLTextAlignmentLeft fontSize:HLFontSizeTitleSmalle];
    [printer appendText:[NSString stringWithFormat:@"包装费：￥%@",_model.MealsFee] alignment:HLTextAlignmentLeft fontSize:HLFontSizeTitleSmalle];
    for (NSDictionary *dic in _model.Discounts) {
        [printer appendText:[NSString stringWithFormat:@"%@：￥%@",dic[@"TypeName"],dic[@"Money"]] alignment:HLTextAlignmentLeft fontSize:HLFontSizeTitleSmalle];
    }
    [printer appendSeperatorLine];
    [printer appendTitle:@"实付：" value:[NSString stringWithFormat:@"￥%@",_model.TotalAmt] fontSize:HLFontSizeTitleSmalle];
    [printer appendSeperatorLine];
    if (_model.Remark.length > 0) {
        [printer appendText:[NSString stringWithFormat:@"备注：%@",_model.Remark] alignment:(HLTextAlignmentLeft) fontSize:(HLFontSizeTitleSmalle)];
        [printer appendSeperatorLine];
    }
    if (_model.Consignee.length > 0|| _model.Tel.length > 0) {
        [printer appendText:[NSString stringWithFormat:@"%@   %@",_model.Consignee,_model.Tel] alignment:(HLTextAlignmentLeft) fontSize:(HLFontSizeTitleSmalle)];
        [printer appendNewLine];
    }
    if (_model.Address.length > 0) {
        [printer appendText:_model.Address alignment:(HLTextAlignmentLeft) fontSize:(HLFontSizeTitleSmalle)];
        [printer appendNewLine];
    }
    [printer appendText:[NSString stringWithFormat:@"配送方式：%@",_model.DeliveryWays] alignment:(HLTextAlignmentLeft) fontSize:(HLFontSizeTitleSmalle)];
    [printer appendSeperatorLine];
    [printer appendText:[self getCurrentTimes] alignment:(HLTextAlignmentLeft) fontSize:(HLFontSizeTitleSmalle)];
    [printer appendText:@"谢谢惠顾,欢迎下次光临!" alignment:HLTextAlignmentCenter fontSize:HLFontSizeTitleSmalle];
    [printer appendNewLine];
    [printer appendNewLine];
    [printer appendNewLine];
    NSData *mainData = [printer getFinalData];
    [[JWBluetoothManage sharedInstance] sendPrintData:mainData completion:^(BOOL completion, CBPeripheral *connectPerpheral,NSString *error) {
        if (completion) {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            VicSingleObject *single=[VicSingleObject getInstance];
            if ([[NSString stringWithFormat:@"%@",[userDefaults objectForKey:[NSString stringWithFormat:@"%@onString",single.shopInfoModel.ShopId]]] isEqualToString:@"开"]||[[NSString stringWithFormat:@"%@",[userDefaults objectForKey:[NSString stringWithFormat:@"%@onString",single.shopInfoModel.ShopId]]] isEqualToString:@"关"]) {
                NSString *countStr = [[userDefaults objectForKey:[NSString stringWithFormat:@"%@countString",single.shopInfoModel.ShopId]] substringWithRange:NSMakeRange(2, 1)];
                NSInteger count = [countStr integerValue];
                if (self->_count==count-1) {
                    self->_count=0;
                    [LocalVoiceFile speakVoice:@"打印完成"];
                    [ProgressShow alertView:[self ViewController].view Message:@"打印完成" cb:nil];
                    [self performSelector:@selector(delayMethod4) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];
                }else{
                    [LocalVoiceFile speakVoice:[NSString stringWithFormat:@"第%ld张打印完成",self->_count+1]];
                    [ProgressShow alertView:[self ViewController].view Message:[NSString stringWithFormat:@"第%ld张打印完成",self->_count+1] cb:nil];
                    self->_count++;
                    [self performSelector:@selector(delayMethod1) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];
                }
            }else{
                self->_count=0;
                [LocalVoiceFile speakVoice:@"打印完成"];
                [ProgressShow alertView:[self ViewController].view Message:@"打印完成" cb:nil];
                [self performSelector:@selector(delayMethod4) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];
            }
        }else{
            NSLog(@"写入错误---:%@",error);
        }
    }];
}
-(void)delayMethod4{
    NSString *shopId3 = [NSString stringWithFormat:@"%@",[self.array lastObject]];
    [self UpdateOrderRequset:shopId3];
}
-(NSString*)getCurrentTimes{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    return currentTimeString;
}
- (void)addMessage:(NSDictionary*)message {
    VLog(@"signalR---------->>>:%@", message);
}
//接单
-(void)UpdateOrderRequset:(NSString *)orderIds{
    NSMutableDictionary *Paramsdic=[NSMutableDictionary new];
    [Paramsdic setValue:[[NSUserDefaults standardUserDefaults]objectForKey:@"token"] forKey:@"token"];
    [Paramsdic setValue:orderIds forKey:@"orderId"];
    [Paramsdic setValue:@(3) forKey:@"state"];//3 待配送
    [ReuserFile updateOrderStateWithParaDic:Paramsdic andBackBlock:^(NSDictionary *backDic) {
        if ([backDic[@"status"] isEqualToString:@"1"]) {
            [LocalVoiceFile speakVoice:@"接单成功，请及时查看"];
        }else{
            [LocalVoiceFile speakVoice:backDic[@"msg"]];
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateHeadView" object:nil];//通知刷新
    }];
}
@end
